package io;

import java.io.File;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA
 * Description:
 * User: Administrator
 * Data: 2023 - 09 - 23
 * Time: 8:35
 */
//IO案例1 扫描指定目录，并找到名称中包含指定字符的所有普通文件（不包含目录），并且后续询问用户是否要删除该文件
public class Demo1 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入要扫描的指定目录：");
        String path = scanner.nextLine();
        File rootPath = new File(path);
        if(!rootPath.isDirectory()) {
            System.out.println("你输入要扫描的指定目录不合法：");
            return;
        }
        System.out.println("请输入要查找文件的关键字：");
        String word = scanner.nextLine();
        scanDir(rootPath, word);
    }
    private static void scanDir(File file, String word) {
        File[] files = file.listFiles();
        if(files == null) return;
        for (File f : files) {
            System.out.println("当前扫描到的文件" + f.getAbsolutePath());
            if(f.isFile()) {
                checkDelete(f, word);
            }else {
                scanDir(f, word);
            }
        }
    }
    private static void checkDelete(File f, String word) {
        if(f.getName().contains(word)) {
            System.out.println("当前文件" + f.getAbsolutePath() + "是否要删除Y/n:");
            Scanner scanner = new Scanner(System.in);
            String choice = scanner.nextLine();
            if (choice.equals("Y") || choice.equals("y")) {
                f.delete();
                System.out.println("删除完毕");
            } else {
                System.out.println("取消删除");
            }
        }
    }
}
